package io.gitee.caoxiaoyu97.log.sensitive.log4j;

import io.gitee.caoxiaoyu97.log.sensitive.pattern.SensitiveDataConverter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
import org.apache.logging.log4j.core.pattern.MessagePatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;
import org.apache.logging.log4j.util.PerformanceSensitive;

import java.util.Arrays;

/*********************************************************
 * 文件名称：Log4jSensitiveDataConverter.java
 * 系统名称：bfts
 * 模块名称：com.hundsun.tbsp.bfts.other.base.log.log4j.pattern
 * 功能说明：
 * 开发人员 @author：caoxy31978
 * 开发时间 @date：2025/9/26 14:24
 * 修改记录：程序版本  修改日期  修改人员  修改单号  修改说明
 *********************************************************/
@Plugin(name = "Log4jSensitiveDataConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({ "m", "msg", "message","sensitive" })
@PerformanceSensitive("allocation")
public class Log4jSensitiveDataConverter extends LogEventPatternConverter {
    MessagePatternConverter messagePatternConverter;
    private Log4jSensitiveDataConverter(MessagePatternConverter messagePatternConverter) {
        super("SensitiveData", "message");
        this.messagePatternConverter = messagePatternConverter;

    }
    public static Log4jSensitiveDataConverter newInstance(final Configuration config, final String[] options) {
        MessagePatternConverter messagePatternConverter = MessagePatternConverter.newInstance(config, options);
        SensitiveDataConverter.init(Arrays.asList(options));
        return new Log4jSensitiveDataConverter(messagePatternConverter);
    }

    @Override
    public void format(LogEvent event, StringBuilder toAppendTo) {
        StringBuilder stringBuilder = new StringBuilder();
        messagePatternConverter.format(event, stringBuilder);
        String convert = SensitiveDataConverter.getInstance().convert(stringBuilder.toString());
        toAppendTo.append(convert);
    }
}
